package JAVAcollectionsanddatastructures.MapandSet;


//***********二叉搜索树************

class Node {
    public int val;
    public Node left;
    public Node right;

    public Node(int val) {
        this.val = val;
    }
}

public class BinarySearchTree {
    Node root = null;

    //查找
    public Node search(int value) {
        Node cur = root;
        while (cur != null) {
            if (cur.val < value) {
                cur = cur.right;
            } else if (cur.val == value) {
                return cur;
            } else {
                cur = cur.left;
            }
        }
        return null;//没有这个数据
    }

    //插入:肯定是插在叶子节点
    public boolean insert(int value) {
        if (root == null) {
            root = new Node(value);
        }
        Node cur = root;
        Node parent = null;
        //找到插入的位置
        while (cur != null) {
            if (cur.val < value) {
                parent = cur;
                cur = cur.right;
            } else if (cur.val > value) {
                parent = cur;
                cur = cur.left;
            } else {
                return false;
            }
        }
        //判断是在左边插入还是右边插入
        Node node = new Node(value);
        if (parent.val < value) {
            parent.right = node;
        } else {
            parent.left = node;
        }
        return true;
    }

    //删除  设待删除结点为 cur, 待删除结点的双亲结点为 parent
    public void remove(Node cur, Node parent) {
        if (cur.left == null) {
            if (cur == root) {
                root = cur.right;
            } else if (cur == parent.left) {
                parent.left = cur.right;
            } else {
                parent.right = cur.right;
            }
        } else if (cur.right == null) {
            if (cur == root) {
                root = cur.left;
            } else if (cur == parent.left) {
                parent.left = cur.left;
            } else {
                parent.right = cur.left;
            }
        } else {//第三种情况没搞懂
            Node targetParent = cur;
            Node target = cur.right;
            while (target.left != null) {
                targetParent = target;
                target = target.left;
            }
            cur.val = target.val;
            if (target == targetParent.left) {
                targetParent.left = target.right;
            } else {
                targetParent.right = target.right;
            }
        }
    }
}
